package cn.arnold.leetcode;

/**
 * @author Arnold-Xiang
 * @Info 进制转换
 */
public class JInZhiConvert {
    public static void main(String[] args) {
        String s = "-1";
        System.out.println(toTwo16(s));
    }

    //10进制转2进制:Integer.toBinaryString是32位：负数会转为32位的2进制
    public static String toTwo32(String s) {
        int n = Integer.parseInt(s);
        String str = Integer.toBinaryString(n);
        String s1 = Integer.toHexString(n);
        System.out.println(s1);
        return str;
    }

    //用16位2进制表示10进制
    public static String toTwo16(String s) {
        int n = Math.abs(Integer.parseInt(s));
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            int temp = n % 2;
            sb.insert(0, temp);
            n = n / 2;
        }
        String str = sb.toString();
        int m = str.length();
        if (m != 16) {
            for (int i = 0; i < 16 - m; i++) {
                str = "0" + str;
            }
        }
        if (Integer.parseInt(s) > 0) {
            return str;
        } else {
            //反码：原码的符号位不变，其他位取反
            StringBuilder sbb = new StringBuilder();
            for (int i = 1; i < str.length(); i++) {
                if (str.charAt(i) == '0') {
                    sbb.append("1");
                } else {
                    sbb.append("0");
                }
            }
            // 符号位不变
            sbb.insert(0,str.charAt(0));
            // 补码：反码加1
            String res = addBinary(sbb.toString(), "1");
            return res;
        }
    }

    //二进制加法
    public static String addBinary(String a, String b) {
        StringBuffer ans = new StringBuffer();
        int n = Math.max(a.length(), b.length()), carry = 0;
        for (int i = 0; i < n; ++i) {
            carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
            carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
            ans.append((char) (carry % 2 + '0'));
            carry /= 2;
        }
        if (carry > 0) {
            ans.append('1');
        }
        ans.reverse();
        return ans.toString();
    }
}
